import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-11-01
 * Time: 22:19
 */
public class UdpEchoClient {
    public DatagramSocket socket;
    //服务器的IP地址和端口号,传送数据时需要知道,放在数据报中
    public String serverIp;
    public int ServerPort;
    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
        socket=new DatagramSocket();//客户端利用系统随机分配的端口号,防止自己手动的端口号不能用
        this.serverIp=serverIp;
        this.ServerPort=serverPort;
    }

    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        while(true){
            //五个步骤
            //1.先接收用户输入的字符串
            System.out.println("->");
            String request=scanner.next();
            //2.构造数据报
            //注意数据报中除了数据内容还要包含服务器IP和端口
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(serverIp),ServerPort);
            //3.发送数据报
            socket.send(requestPacket);
            //4.从服务器接收响应,并解析
            DatagramPacket responsePacket=new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            //解析数据
            String response=new String(responsePacket.getData(),0,
                    responsePacket.getLength(),"UTF-8");//同样注意这里求长度用的也是数据报
            //5.打印在控制台上
            System.out.printf("req:%s resp:%s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        //如果服务器在其他机器上就需要将IP地址和端口号更改了
        UdpEchoClient udpEchoClient=new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
